<?php

namespace services\user;

use common\components\Service;
use common\helpers\DateHelper;
use common\models\user\User;
use common\models\wechat\WechatTemplate;
use services\linkedcare\LinkedcarePatientsFeeDetailService;
use services\linkedcare\LinkedcarePatientsRecordService;
use services\patient\PatientService;
use services\wechat\WechatTemplateService;
use Yii;

class UserService extends Service
{
    /**
     * 小程序【我的】
     * @return array
     */
    public function myInfo(): array
    {
        $spoker = Yii::$app->user->identity->user->spoker;
        $avatar = Yii::$app->user->identity->user->avatar_url ?: '1.png';
        return [
            'mobile' => $spoker->mobile,
            'avatar_url' => Yii::$app->params['api_url']."/avatar/{$avatar}",
            'level_name' => '普通代言人',
        ];
    }

    /**
     * 统计用户数据
     * @return array
     */
    public function getUserStatisticsData(array $params = []): array
    {
        $condition = [
            'start_time' => $params['start_time'] ?? '',
            'end_time' => $params['end_time'] ?? '',
        ];

        return [
            'patient_num' => PatientService::getUserPatientNum($condition),
            'arrive_num' => LinkedcarePatientsRecordService::getUserArriveNum($condition),
            'consume_money' => LinkedcarePatientsFeeDetailService::getUserConsumeMoney($condition),
        ];
    }

    /**
     * 新增用户
     * @param string $openid
     * @return User
     * @throws \Exception
     */
    public static function createUser(string $openid): User
    {
        $index = mt_rand(1, 6);
        $user = new User();
        $user->wx_mini_openid = $openid;
        $user->status = User::STATUS_ENABLE;
        $user->avatar_url = "{$index}.png";
        $user->saveAndCheckResult();
        return $user;
    }

    /**
     * 更新用户授权手机号
     * @param string $mobile
     * @return void
     * @throws \Exception
     */
    public static function updateWxMobile(string $mobile): void
    {
        if (empty($mobile)) {
            return;
        }
        /**
         * @var User $user
         */
        $user = Yii::$app->user->identity->user;
        if (empty($user)) {
            throw new \Exception('用户不存在', 422);
        }
        $user->mobile = $mobile;
        $user->saveAndCheckResult();
    }

    /**
     * 月账单通知
     * @return void
     */
    public function getUserMonthBill(): void
    {
        $lastMonth = DateHelper::lastMonth();
        $condition = [
            'start_time' => DateHelper::timestampToDate($lastMonth['start'], DateHelper::DATE_FORMAT_1),
            'end_time' => DateHelper::timestampToDate($lastMonth['end'], DateHelper::DATE_FORMAT_1),
        ];
        $addPatientData = PatientService::getMonthBillByUser($condition);
        $arrivePatientData = LinkedcarePatientsRecordService::getMonthBillByUser($condition);
        $consumePatientData = LinkedcarePatientsFeeDetailService::getMonthBillByUser($condition);
        $userIds = array_merge(array_keys($addPatientData), array_keys($arrivePatientData), array_keys($consumePatientData));

        $userList = User::findAll(['id' => $userIds]);
        $month = date('m', $lastMonth['start']);
        foreach ($userList as $user) {
            $sendData = [
                'number1' => $addPatientData[$user->id]['add_num'] ?? 0,
                'number2' => $arrivePatientData[$user->id]['arrive_num'] ?? 0,
                'amount3' => $consumePatientData[$user->id]['actual_price'] ?? 0,
                'thing4' => "{$month}月的代言，请核对，谢谢您的努力",
            ];
            WechatTemplateService::sendTemplate(WechatTemplate::TYPE_MONTH_BILL, $sendData, $user->wx_mini_openid);
        }
    }
}